﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using TecBaseObjects.Interfaces;
using TecBaseObjects.Models.BusinessCases;
using TecBaseObjects.Objects;
using TecContracts;
using TecData.Manager;
using TpOffice.Forms.BusinessCase;
using TecTools;
using TecExtensions;
using TpGlobalForms.Forms;
using System.Text;


namespace TpOffice.Controller.BusinessCase {

    public class BusinessCaseMainController : IController {

        #region Members

        BusinessCaseMainForm myForm;
        byte currentProjectStatus;
        int currentOrgKey;

        #endregion

        #region Constructor

        public BusinessCaseMainController(BusinessCaseMainForm form) {
            this.myForm = form;
        }

        #endregion

        #region Methods

        private void ChangedProperties(object sender, PropertyChangedEventArgs e) {

            #region Business Checkbox

            if (e.PropertyName == "Business") {
                this.myForm.MyModel.ShortName = GetProjectShortName(this.myForm.MyModel);
            }

            #endregion

            #region ShortName

            if (e.PropertyName == "ShortName") {
                Debug.Print("ShortName");
            }

            #endregion

            #region Purchaser

            if (e.PropertyName == "Purchaser") {
                Organisation org = OrganisationDataManager.LoadOrganisation(this.myForm.MyModel.Purchaser);
                if (this.myForm.MyModel.ShortName == null
                    || this.myForm.MyModel.ShortName == ""
                    || !this.myForm.MyModel.Saved) {
                    this.myForm.MyModel.ShortName = GetProjectShortName(this.myForm.MyModel);
                }
                if (this.myForm.MyModel.InvoiceRecipient == 0
                    || !this.myForm.MyModel.Saved) {
                    this.myForm.MyModel.InvoiceRecipient = this.myForm.MyModel.Purchaser;
                    
                    if (org.OrgName.Left(2) == "Wh") {
                        this.myForm.MyModel.InvoiceRecipient = OrganisationDataManager.LoadOrganisation("Wunschhaus", 2334).OrgKey;
                    }
                }
                if (this.myForm.MyModel.ProjectAddress == null 
                    || this.myForm.MyModel.ProjectAddress == ""
                    || !this.myForm.MyModel.Saved) {
                    this.myForm.MyModel.ProjectAddress = org.Straße;
                }
                if (this.myForm.MyModel.ProjectEPLZ == 0
                    || !this.myForm.MyModel.Saved) {
                    this.myForm.MyModel.ProjectEPLZ = org.EPLZ;
                }
            }

            #endregion

            #region ProjectStatus

            if (e.PropertyName == "ProjectStatus") {
                CheckProjectStatusBeforeChanging(this.myForm.MyModel);
                //if (this.myForm.MyModel.ProjectStatus != currentProjectStatus) {
                //    ComboBox cmb = sender as ComboBox;
                //    cmb.SelectedValue = currentProjectStatus - 1;
                //}
            }

            #endregion

            #region CustomerSource

            if (e.PropertyName == "CustomerSource") {
                if (this.myForm.MyCustomerSourceModel[this.myForm.MyModel.CustomerSource - 1].CustomerSourceShort == "Wh") {
                    this.myForm.MyModel.FilePath = String.Format(this.myForm.MyBusinessCaseStatusModel[this.myForm.MyModel.ProjectStatus - 1].FilePath, DateTime.Now.Date.Year.ToString().Right(2), "Wh");
                }
            }

            #endregion

            #region EPLZ and Address

            if (e.PropertyName == "ProjectEPLZ" || e.PropertyName == "ProjectAddress") {
                if (this.myForm.MyModel.ProjectEPLZ != 0 && (this.myForm.MyModel.ProjectAddress != null && this.myForm.MyModel.ProjectAddress != "")) {
                    PlzOrt pl = CommonDataManager.LoadPlzOrt(this.myForm.MyModel.ProjectEPLZ);
                    string targetAddress = pl.Plz + " " + pl.Ort + ", " + this.myForm.MyModel.ProjectAddress;
                    this.myForm.MyModel.Distance = Tools.GetDistance(Extensions.tpStartAddress, targetAddress);
                }
            }

            #endregion

            #region IsDirty

            if (e.PropertyName != "IsDirty") {
                this.myForm.MyModel.IsDirty = true;
            }

            #endregion

        }

        
        private bool CheckForm(BusinessCaseModel model) {
            bool ret = true;
            StringBuilder msg = new StringBuilder();

            if (model.ShortName == null || model.ShortName == "") {
                msg.AppendLine("Geschäftsfall muss anggeben werden.");
            }
            if (model.Purchaser == 0) {
                msg.AppendLine("Auftraggeber nuss ausgewählt werden");
            }
            if (model.InvoiceRecipient == 0) {
                msg.AppendLine("Rechnungsempfänger muss ausgewählt werden.");
            }
            if (model.ProjectAddress == null || model.ProjectAddress == "") {
                msg.AppendLine("Straße mit Hausnummer muss einggeben werden.");
            }
            if (model.ProjectEPLZ == 0) {
                msg.AppendLine("Plz/Ort muss ausgewählt werden.");
            }
            if (model.CustomerSource == 0) {
                msg.AppendLine("Kundenquelle muss ausgewählt werden.");
            }
            if (msg.ToString() != "") {
                MessageBox.Show(msg.ToString(), "Tec-Office", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ret = false;
            }
            return ret;
        }

        public void CheckKalkulationLink(object sender, EventArgs e) {
            LinkLabel llCalc = sender as LinkLabel;
            string linkFile = Path.Combine(this.myForm.MyModel.FilePath, llCalc.Text + ".xlsm");
            if (!File.Exists(linkFile)) {
                string msg = "Die angegebene Kalkulations-Datei existiert nicht. Soll sie neu angelegt werden?";
                DialogResult res = MessageBox.Show(msg, "Tec-Office", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (res == DialogResult.Yes) {
                    //create a new calculation file!
                    Office.CreateCalculationFile(linkFile, this.myForm.MyModel, Contracts.MyUser.LoginName.Trim());
                }
                if (res == DialogResult.No) {
                    return;
                }
            }
            Office.OpenExcelFile(linkFile);
        }

        public void CheckProjectStatusBeforeChanging(BusinessCaseModel model) {
            string sourcePath = model.FilePath;
            string sourceFile = model.ShortName;
            string linkFile = Path.Combine(sourcePath, sourceFile + "." + Extensions.DocExt.XlsM);
            string searchPattern = model.ShortName + "*";
            if (model.ProjectStatus != currentProjectStatus) {
                if (File.Exists(linkFile)) {
                    string targetPath = String.Format(this.myForm.MyBusinessCaseStatusModel[model.ProjectStatus - 1].FilePath, DateTime.Now.Date.Year.ToString().Right(2), this.myForm.MyModel.ShortName.Left(1));
                    string msg = "Sollen die bestehende Kalkulationsdatei und alle Projektdateien nach {0} verschoben werden?";
                    msg = String.Format(msg, targetPath);
                    DialogResult res = MessageBox.Show(msg, "Tec-Office", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (res == DialogResult.Yes) {
                        if (Tools.MoveFiles(sourcePath, targetPath, searchPattern)) {
                            this.myForm.MyModel.FilePath = targetPath;
                            currentProjectStatus = model.ProjectStatus;
                            msg = "Dateien wurden erfolgreich verschoben!";
                            MessageBox.Show(msg, "Tec-Office", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        } else {
                            throw new Exception("Fehler beim verschieben der Dateien!");
                        }
                    }
                    if (res == DialogResult.No) {
                        //model.ProjectStatus = currentProjectStatus;
                    }
                }
            }
        }

        public void CreateNewOrganisation(object sender, EventArgs e) {
            currentOrgKey = 0;
            OpenOrganisation(currentOrgKey);
            if (currentOrgKey != 0) {
                this.myForm.MyPurchaserModel = CommonDataManager.LoadOrganisationsShortList();
                this.myForm.MyInvoiceRecipientModel = this.myForm.MyPurchaserModel;
            }
        }

        public void Dispose() {

        }

        public void LoadModels(int businessCaseID) {
            this.myForm.MyModel = BusinessCaseDataManager.LoadBusinessCase(businessCaseID);
            if (businessCaseID <= 0) {
                SetDefaultValues(this.myForm.MyModel);
            }
            this.myForm.MyModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(ChangedProperties);
            this.myForm.MyPurchaserModel = CommonDataManager.LoadOrganisationsShortList();
            this.myForm.MyInvoiceRecipientModel = this.myForm.MyPurchaserModel;
            this.myForm.MyFirstContactUserModel = TecUserDataManager.LoadTecUser(false);
            this.myForm.MyCalculationUserModel = this.myForm.MyFirstContactUserModel;
            this.myForm.MySalesUserModel = this.myForm.MyFirstContactUserModel;
            this.myForm.MyFileUserModel = this.myForm.MyFirstContactUserModel;
            this.myForm.MyBusinessCaseStatusModel = BusinessCaseDataManager.LoadBusinessCaseStatusList();
            this.myForm.MyPlzOrtModel = CommonDataManager.LoadPlzOrtList();
            this.myForm.MyCustomerSourceModel = BusinessCaseDataManager.LoadCustomerSourceList();
            this.currentProjectStatus = this.myForm.MyModel.ProjectStatus;
        }

        public void OpenOrganisation(int orgKey) {
            Organisation org = OrganisationDataManager.LoadOrganisation(orgKey);
            if (org == null) {
                org = new Organisation();
            }
            OrganisationForm orgFrom = new OrganisationForm(org);
            orgFrom.ShowDialog();
        }

        public void Save(IBaseObject myObject) {
            BusinessCaseModel model = myObject as BusinessCaseModel;
            if (CheckForm(model)) {
                BusinessCaseDataManager.SaveBusinessCase(model);
                model.IsDirty = false;
            }
        }

        public void SetDefaultValues(BusinessCaseModel model) {
            model.ProjectStatus = 1;
            model.FilePath = @"T:\Anfr\" + DateTime.Now.Date.ToString().Right(2) + @"\";
            model.FirstContactUserID = Contracts.MyUser.UserID;
            model.CalculationUserID = Contracts.MyUser.UserID;
            model.SalesUserID = Contracts.MyUser.UserID;
            model.FileUserID = Contracts.MyUser.UserID;
            model.FirstContactDate = DateTime.Now.Date;
            model.OrderDate = DateTime.Now.Date;
            model.FinishDate = DateTime.Now.Date;
            model.ImplementationDate = DateTime.Now.Date;
            model.CreatedOn = DateTime.Now;
            model.CreatedBy = Contracts.MyUser.LoginName.Trim();

        }

        public void SetFormTitle(string title) {
            this.myForm.Text = title;
        }

        public void SetFormStatusLabelText() {
            string txt = "Angelegt: " + this.myForm.MyModel.CreatedOn.ToString("yy-MM-dd HH:mm");
            if (this.myForm.MyModel.CreatedBy != null && this.myForm.MyModel.CreatedBy.Length > 0) {
                txt += " von " + this.myForm.MyModel.CreatedBy.Trim();
            }
            this.myForm.SetFormStatusLabelText(txt);
        }

        #endregion

        #region Functions

        public void BeforeCloseMyForm(object sender, FormClosingEventArgs e) {
            if (this.myForm.MyModel.IsDirty) {
                DialogResult res = MessageBox.Show("Datensatz wurde noch nicht gespeichert. Wollen Sie jetzt speichern?", "Barverkauf", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
                if (res == DialogResult.Yes) {
                    this.Save(this.myForm.MyModel);
                    return;
                }
                if (res == DialogResult.No) {
                    return;
                }
            } else {
                return;
            }
            return;
        }
        
        private string GetProjectShortName(BusinessCaseModel model) {
            string ret = DateTime.Now.Date.Year.ToString().Right(2) + "p" + (model.Business ? "0" : "") + "1";
            Organisation org = OrganisationDataManager.LoadOrganisation(model.Purchaser);
            if (org != null) {
                int projectCount = BusinessCaseDataManager.GetPurchaserProjectCount(org.OrgKey, model.FirstContactDate.Year);
                if (!model.Saved) {
                    projectCount++;
                }
                int namesCount = BusinessCaseDataManager.GetPurchaserNamesCount(org.OrgKey, model.FirstContactDate.Year);
                ret = org.OrgName 
                        + DateTime.Now.Date.Year.ToString().Right(2) 
                        + (model.Business ? "0" : "")
                        + namesCount.ToString()
                        + "p" 
                        + projectCount.ToString();
            }
            return ret;
        }

        #endregion

    }
}
